package user;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class Auth
 */
@WebServlet("/Auth")
public class Auth extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Auth() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		//response.getWriter().append("Served at: ").append(request.getContextPath());
		BufferedImage bi = new BufferedImage(68,22,BufferedImage.TYPE_INT_RGB);
        //为bi创建图形上下文
        Graphics g = bi.getGraphics();
        //设置颜色，此处调用的构造方法是基于RGB数值作为参数的
        Color c = new Color(200,150,255);
        //设置颜色          
        g.setColor(c);
        //该方法用于填充指定的矩形，参数是坐标和宽高
        g.fillRect(0,0,68,22);
        
//编写随机获取验证码的部分
        
        //将字符串转换为字符数组
        char[] ch = "abcdefghijklmnopqrstuvwxyz0123456789".toCharArray();
        //随机类，在本程序中只使用了 int nextInt(int n) 方法，作用是生成一个0-n的伪随机int值
        Random r = new Random();
        
        int len = ch.length,index;
        
        //用于存储随机生成的四位验证码
        StringBuffer sb = new StringBuffer();
        
        for(int i = 0;i < 4;i++) {
            //从0-len随机获取一个作为下标
            index = r.nextInt(len);
            //随机获取颜色
            g.setColor(new Color(r.nextInt(200),r.nextInt(150),r.nextInt(255)));
            
            //在图形中绘制指定的String，参数对应要绘制的String以及坐标
            g.drawString(ch[index]+" ",(i*15)+3,18);
            
            //将内容添加到StringBuffer
            sb.append(ch[index]);
        }
        
        //将验证码信息放入session中用于验证
        request.getSession().setAttribute("PicCode", sb.toString());
        //将文件流输出，参数要写入的RenderedImage，输出的文件格式，输出到的ImageOutputStream
        ImageIO.write(bi,"JPG",response.getOutputStream());
    }
	

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
